package com.firewolf.springcloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 作者：刘兴
 * 时间:19/2/18
 **/
//@Component
public class LoginFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    //过滤器要处理的逻辑
    @Override
    public Object run() throws ZuulException {
        //希望name字段的值是admin
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String name = request.getParameter("name");
        if (name == null || !"admin".equals(name)) {
            currentContext.setSendZuulResponse(false); //停止路由请求
            //通过状态码来标识请求的结果
            currentContext.setResponseStatusCode(500); //状态嘛
            currentContext.setResponseBody("错误信息"); //返回错误信息
        } else {
            currentContext.setSendZuulResponse(true); //继续请求
            currentContext.setResponseStatusCode(200);
        }
        return null; //因为需要请求，所以此处不返回数据
    }
}
